import UIKit
import Photos

class EditViewController: UIViewController {
    
    // MARK: - UI Elements
    private var imageView: UIImageView!
    private var filterCollectionView: UICollectionView!
    private var intensitySlider: UISlider!
    private var intensityLabel: UILabel!
    private var saveButton: UIButton!
    private var shareButton: UIButton!
    private var cancelButton: UIButton!
    private var compareButton: UIButton!
    private var bottomToolsView: UIView!
    
    // MARK: - Properties
    var inputImage: UIImage!
    private let filterEngine = FilterEngine()
    private let shareManager = ShareManager()
    private var filteredImage: UIImage!
    private var currentFilterType: FilterType = .original
    private var currentIntensity: Float = 1.0
    private var isShowingOriginal = false
    
    // Filter preview images for better performance
    private var filterPreviews: [UIImage] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        loadImage()
        generateFilterPreviews()
    }
    
    // MARK: - UI Setup
    private func setupUI() {
        view.backgroundColor = .black
        
        // Setup image view
        imageView.contentMode = .scaleAspectFit
        imageView.backgroundColor = .black
        
        // Setup intensity slider
        intensitySlider.minimumValue = 0.0
        intensitySlider.maximumValue = 1.0
        intensitySlider.value = currentIntensity
        intensitySlider.addTarget(self, action: #selector(intensityChanged(_:)), for: .valueChanged)
        
        // Setup buttons
        setupButtons()
        
        // Setup bottom tools view
        bottomToolsView.backgroundColor = UIColor.black.withAlphaComponent(0.8)
        
        // Setup intensity label
        intensityLabel.text = "\(Int(currentIntensity * 100))%"
        intensityLabel.textColor = .white
        intensityLabel.font = UIFont.systemFont(ofSize: 14)
        
        // Add long press gesture to compare button
        let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(compareButtonLongPressed(_:)))
        compareButton.addGestureRecognizer(longPressGesture)
    }
    
    private func setupButtons() {
        let buttons = [saveButton, shareButton, cancelButton, compareButton]
        
        buttons.forEach { button in
            button?.layer.cornerRadius = 8
            button?.backgroundColor = UIColor.systemBlue
            button?.setTitleColor(.white, for: .normal)
            button?.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        }
        
        cancelButton.backgroundColor = UIColor.systemGray
        compareButton.backgroundColor = UIColor.systemOrange
    }
    
    private func setupFilterCollectionView() {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.itemSize = CGSize(width: 80, height: 100)
        layout.minimumInteritemSpacing = 10
        layout.minimumLineSpacing = 10
        layout.sectionInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
        
        filterCollectionView.collectionViewLayout = layout
        filterCollectionView.delegate = self
        filterCollectionView.dataSource = self
        filterCollectionView.backgroundColor = .clear
        filterCollectionView.showsHorizontalScrollIndicator = false
        
        // Register cell
        filterCollectionView.register(EditFilterCell.self, forCellWithReuseIdentifier: "EditFilterCell")
    }
    
    private func loadImage() {
        guard let inputImage = inputImage else { return }
        imageView.image = inputImage
        filteredImage = inputImage
    }
    
    private func generateFilterPreviews() {
        guard let inputImage = inputImage else { return }
        
        DispatchQueue.global(qos: .userInteractive).async { [weak self] in
            guard let self = self else { return }
            
            let previews = self.filterEngine.generateFilterPreviews(for: inputImage)
            
            DispatchQueue.main.async {
                self.filterPreviews = previews
                self.filterCollectionView.reloadData()
            }
        }
    }
    
    // MARK: - Actions
    @IBAction func cancelButtonTapped(_ sender: UIButton) {
        dismiss(animated: true)
    }
    
    @IBAction func saveButtonTapped(_ sender: UIButton) {
        guard let imageToSave = isShowingOriginal ? inputImage : filteredImage else { return }
        
        PHPhotoLibrary.requestAuthorization { [weak self] status in
            if status == .authorized {
                DispatchQueue.main.async {
                    self?.saveImageToPhotoLibrary(imageToSave)
                }
            } else {
                DispatchQueue.main.async {
                    self?.showAlert(title: "权限错误", message: "需要相册访问权限来保存照片")
                }
            }
        }
    }
    
    @IBAction func shareButtonTapped(_ sender: UIButton) {
        guard let imageToShare = isShowingOriginal ? inputImage : filteredImage else { return }
        shareManager.shareImage(imageToShare, from: self)
    }
    
    @IBAction func compareButtonTapped(_ sender: UIButton) {
        toggleImageComparison()
    }
    
    @objc private func compareButtonLongPressed(_ gesture: UILongPressGestureRecognizer) {
        switch gesture.state {
        case .began:
            showOriginalImage()
        case .ended, .cancelled:
            showFilteredImage()
        default:
            break
        }
    }
    
    @objc private func intensityChanged(_ slider: UISlider) {
        currentIntensity = slider.value
        intensityLabel.text = "\(Int(currentIntensity * 100))%"
        applyCurrentFilter()
    }
    
    // MARK: - Filter Application
    private func applyCurrentFilter() {
        guard let inputImage = inputImage else { return }
        
        DispatchQueue.global(qos: .userInteractive).async { [weak self] in
            guard let self = self else { return }
            
            let filtered = self.filterEngine.applyFilter(
                to: inputImage,
                filterType: self.currentFilterType,
                intensity: self.currentIntensity
            )
            
            DispatchQueue.main.async {
                self.filteredImage = filtered
                if !self.isShowingOriginal {
                    self.imageView.image = filtered
                }
            }
        }
    }
    
    // MARK: - Image Comparison
    private func toggleImageComparison() {
        isShowingOriginal.toggle()
        updateImageDisplay()
        updateCompareButtonTitle()
    }
    
    private func showOriginalImage() {
        isShowingOriginal = true
        updateImageDisplay()
        compareButton.backgroundColor = UIColor.systemRed
    }
    
    private func showFilteredImage() {
        isShowingOriginal = false
        updateImageDisplay()
        compareButton.backgroundColor = UIColor.systemOrange
    }
    
    private func updateImageDisplay() {
        UIView.transition(with: imageView, duration: 0.2, options: .transitionCrossDissolve) { [weak self] in
            guard let self = self else { return }
            self.imageView.image = self.isShowingOriginal ? self.inputImage : self.filteredImage
        }
    }
    
    private func updateCompareButtonTitle() {
        let title = isShowingOriginal ? "显示滤镜" : "显示原图"
        compareButton.setTitle(title, for: .normal)
    }
    
    // MARK: - Save Image
    private func saveImageToPhotoLibrary(_ image: UIImage) {
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
    }
    
    @objc private func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
        if let error = error {
            showAlert(title: "保存失败", message: error.localizedDescription)
        } else {
            showAlert(title: "保存成功", message: "照片已保存到相册")
        }
    }
    
    // MARK: - Helper Methods
    private func showAlert(title: String, message: String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .default))
        present(alert, animated: true)
    }
}

// MARK: - UICollectionViewDataSource & Delegate
extension EditViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return FilterType.allCases.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "EditFilterCell", for: indexPath) as! EditFilterCell
        
        let filterType = FilterType.allCases[indexPath.item]
        let isSelected = filterType == currentFilterType
        
        let previewImage = indexPath.item < filterPreviews.count ? filterPreviews[indexPath.item] : nil
        
        cell.configure(
            with: filterType.name,
            previewImage: previewImage,
            isSelected: isSelected
        )
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let newFilterType = FilterType.allCases[indexPath.item]
        
        // Only apply if different filter is selected
        if newFilterType != currentFilterType {
            currentFilterType = newFilterType
            applyCurrentFilter()
            collectionView.reloadData()
            
            // Enable/disable intensity slider based on filter type
            intensitySlider.isEnabled = newFilterType != .original
            intensityLabel.isHidden = newFilterType == .original
        }
    }
}

// MARK: - Edit Filter Collection View Cell
class EditFilterCell: UICollectionViewCell {
    private let titleLabel = UILabel()
    private let previewImageView = UIImageView()
    private let selectionIndicator = UIView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupCell()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupCell()
    }
    
    private func setupCell() {
        backgroundColor = UIColor.white.withAlphaComponent(0.1)
        layer.cornerRadius = 8
        
        // Setup preview image view
        previewImageView.contentMode = .scaleAspectFill
        previewImageView.clipsToBounds = true
        previewImageView.layer.cornerRadius = 6
        previewImageView.backgroundColor = UIColor.gray.withAlphaComponent(0.3)
        
        // Setup title label
        titleLabel.textAlignment = .center
        titleLabel.font = UIFont.systemFont(ofSize: 11, weight: .medium)
        titleLabel.textColor = .white
        titleLabel.numberOfLines = 1
        
        // Setup selection indicator
        selectionIndicator.backgroundColor = UIColor.systemBlue
        selectionIndicator.layer.cornerRadius = 2
        selectionIndicator.isHidden = true
        
        addSubview(previewImageView)
        addSubview(titleLabel)
        addSubview(selectionIndicator)
        
        // Auto Layout
        previewImageView.translatesAutoresizingMaskIntoConstraints = false
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        selectionIndicator.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            // Preview image
            previewImageView.topAnchor.constraint(equalTo: topAnchor, constant: 8),
            previewImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8),
            previewImageView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8),
            previewImageView.heightAnchor.constraint(equalToConstant: 60),
            
            // Title label
            titleLabel.topAnchor.constraint(equalTo: previewImageView.bottomAnchor, constant: 4),
            titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 4),
            titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -4),
            titleLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -4),
            
            // Selection indicator
            selectionIndicator.bottomAnchor.constraint(equalTo: previewImageView.bottomAnchor, constant: -4),
            selectionIndicator.trailingAnchor.constraint(equalTo: previewImageView.trailingAnchor, constant: -4),
            selectionIndicator.widthAnchor.constraint(equalToConstant: 8),
            selectionIndicator.heightAnchor.constraint(equalToConstant: 8)
        ])
    }
    
    func configure(with title: String, previewImage: UIImage?, isSelected: Bool) {
        titleLabel.text = title
        previewImageView.image = previewImage
        
        // Update selection state
        selectionIndicator.isHidden = !isSelected
        backgroundColor = isSelected ? 
            UIColor.systemBlue.withAlphaComponent(0.3) : 
            UIColor.white.withAlphaComponent(0.1)
        
        // Update border
        layer.borderWidth = isSelected ? 2 : 0
        layer.borderColor = isSelected ? UIColor.systemBlue.cgColor : UIColor.clear.cgColor
    }
    
    override func prepareForReuse() {
        super.prepareForReuse()
        previewImageView.image = nil
        selectionIndicator.isHidden = true
        backgroundColor = UIColor.white.withAlphaComponent(0.1)
        layer.borderWidth = 0
    }
}